/*
 * Created by: Peter Weissbrod
 * Created: Saturday, November 03, 2007
 */
using System;
using EntityLayer;
using EntityLayer.Entities;
using Utils;

namespace Controllers
{
    public class SalesItemController : ControllerBase<SalesItem>
    {
        #region methods
        public SalesItemController(ISalesItemManagementView salesItemManagementView) : base(salesItemManagementView)
        {
            salesItemManagementView.UpdateSalesItemEvent +=
                new EventHandler<SalesItemEventArgs>(salesItemManagementView_UpdateSalesItemEvent);
            salesItemManagementView.CreateSalesItemEvent +=
                new EventHandler<SalesItemEventArgs>(salesItemManagementView_CreateSalesItemEvent);
        }
        private void salesItemManagementView_UpdateSalesItemEvent(object sender, SalesItemEventArgs e)
        {
            SalesItem salesItem = e.SalesItem;
            Check.Assert(salesItem.SalesItemID != Nulls.ID, "Cant find the salesItemID");
            ValidateData(salesItem);
            salesItem.UpdateAndFlush();
        }
        private void salesItemManagementView_CreateSalesItemEvent(object sender, SalesItemEventArgs e)
        {
            SalesItem salesItem = e.SalesItem;
            ValidateData(salesItem);
            salesItem.SaveAndFlush();
        }
        #endregion
        /// <summary>
        /// If the incoming data is invalid, an exception will be thrown here
        /// </summary>
        /// <param name="t"></param>
        protected override void ValidateData(SalesItem t)
        {
            if(t is Book)
                ValidateData(t as Book);
            if(t is Media)
                ValidateData(t as Media);
            Check.Assert(SalesItem.FindAllByProperty("Name",t.Name).Length==0,"A SalesItem of this name already exists.");
            Check.Assert(t.Name.Length>0,"The name must be provided");
        }
        private void ValidateData(Book book)
        {
            Check.Assert(book.Year>0);
            Check.Assert(book.NumPages>0);
        }
        private void ValidateData(Media media)
        {
            Check.Assert(media.MediaType!=Enumerations.MediaTypes.Null, "MediaType was not specified");
        }
    }
}